<template>
  <div class="student-class-container">
    <el-card class="header-card">
      <div class="header-content">
        <h2>我的班级</h2>
        <el-button @click="loadClasses">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </el-card>

    <!-- 班级信息 -->
    <div v-if="classes.length > 0">
      <el-row :gutter="20">
        <el-col :span="24" v-for="classItem in classes" :key="classItem.id">
          <el-card class="class-card" shadow="hover">
            <template #header>
              <div class="class-header">
                <h3>{{ classItem.name }}</h3>
                <el-tag :type="classItem.status === 'active' ? 'success' : 'info'">
                  {{ classItem.status === 'active' ? '活跃' : '停用' }}
                </el-tag>
              </div>
            </template>
            
            <div class="class-info">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="班级描述">
                  {{ classItem.description || '无描述' }}
                </el-descriptions-item>
                <el-descriptions-item label="班主任">
                  {{ classItem.teacher_name }}
                </el-descriptions-item>
                <el-descriptions-item label="班级人数">
                  <el-tag :type="classItem.current_students >= classItem.max_students ? 'danger' : 'success'">
                    {{ classItem.current_students }}/{{ classItem.max_students }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">
                  {{ formatDate(classItem.created_at) }}
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <div class="class-actions">
              <el-button type="primary" @click="viewClassAssignments(classItem)">
                <el-icon><List /></el-icon>
                查看作业
              </el-button>
              <el-button @click="viewClassStudents(classItem)">
                <el-icon><User /></el-icon>
                班级同学
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 班级作业列表 -->
      <el-card class="assignments-card" v-if="showAssignments && currentClassAssignments.length > 0">
        <template #header>
          <div class="card-header">
            <span>{{ currentClassName }} - 班级作业</span>
            <el-button text @click="showAssignments = false">
              <el-icon><Close /></el-icon>
              关闭
            </el-button>
          </div>
        </template>

        <el-table :data="currentClassAssignments" v-loading="assignmentsLoading" style="width: 100%">
          <el-table-column prop="title" label="作业标题" min-width="200">
            <template #default="{ row }">
              <el-link type="primary" @click="viewAssignmentDetail(row)">{{ row.title }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="due_date" label="截止时间" width="180">
            <template #default="{ row }">
              <el-tag :type="isExpired(row.due_date) ? 'danger' : 'success'">
                {{ formatDate(row.due_date) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="total_score" label="总分" width="80" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="goToAssignment(row)">
                {{ row.status === 'completed' ? '查看' : '开始' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 班级同学列表 -->
      <el-dialog v-model="showStudentsDialog" :title="`${currentClassName} - 班级同学`" width="600px">
        <el-table :data="currentClassStudents" v-loading="studentsLoading" style="width: 100%">
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="username" label="用户名" width="150" />
          <el-table-column prop="email" label="邮箱" min-width="200" />
          <el-table-column prop="created_at" label="加入时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>

    <!-- 空状态 -->
    <div v-else-if="!loading" class="empty-state">
      <el-empty description="您还没有加入任何班级">
        <el-button type="primary" @click="$router.push('/dashboard')">返回首页</el-button>
      </el-empty>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <el-card>
        <el-skeleton :rows="3" animated />
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh, List, User, Close } from '@element-plus/icons-vue'
import { classesApi, type Class } from '@/api/classes'

const router = useRouter()

// 数据
const classes = ref<Class[]>([])
const loading = ref(false)
const assignmentsLoading = ref(false)
const studentsLoading = ref(false)
const showAssignments = ref(false)
const showStudentsDialog = ref(false)
const currentClassAssignments = ref<any[]>([])
const currentClassStudents = ref<any[]>([])
const currentClassName = ref('')

// 加载班级列表
const loadClasses = async () => {
  loading.value = true
  try {
    const response = await classesApi.getClasses()
    classes.value = response
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '加载班级列表失败')
    console.error('加载班级列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查看班级作业
const viewClassAssignments = async (classItem: Class) => {
  currentClassName.value = classItem.name
  assignmentsLoading.value = true
  showAssignments.value = true
  
  try {
    const response = await classesApi.getClassAssignments(classItem.id)
    currentClassAssignments.value = response
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '加载班级作业失败')
    console.error('加载班级作业失败:', error)
  } finally {
    assignmentsLoading.value = false
  }
}

// 查看班级同学
const viewClassStudents = async (classItem: Class) => {
  currentClassName.value = classItem.name
  studentsLoading.value = true
  showStudentsDialog.value = true
  
  try {
    const response = await classesApi.getClassDetail(classItem.id)
    currentClassStudents.value = response.students || []
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || '加载班级同学失败')
    console.error('加载班级同学失败:', error)
  } finally {
    studentsLoading.value = false
  }
}

// 查看作业详情
const viewAssignmentDetail = (assignment: any) => {
  ElMessage.info(`查看作业: ${assignment.title}`)
}

// 前往作业
const goToAssignment = (assignment: any) => {
  router.push(`/homeworks/${assignment.id}`)
}

// 检查是否过期
const isExpired = (dueDateString: string) => {
  return new Date(dueDateString) < new Date()
}

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    'active': 'success',
    'completed': 'info',
    'overdue': 'danger',
    'draft': 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'active': '进行中',
    'completed': '已完成',
    'overdue': '已过期',
    'draft': '草稿'
  }
  return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

onMounted(() => {
  loadClasses()
})
</script>

<style scoped>
.student-class-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.class-card {
  margin-bottom: 20px;
}

.class-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.class-header h3 {
  margin: 0;
  color: #303133;
}

.class-info {
  margin-bottom: 20px;
}

.class-actions {
  display: flex;
  gap: 10px;
}

.assignments-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.loading-state {
  padding: 20px 0;
}
</style>
